
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');

/**
 * req: 
 * resp:
 * root: 静态资源的根路径
 */
exports.staticServer = (req, resp, root) => {
    fs.readFile(path.join(root,req.url),(err, fileContent)=>{
        if (err) {
            resp.writeHead(404, {
                'Content-Type': 'text/plain; charset=utf8'
            });
            resp.end('资源不存在！');
        } else {
            let ext = path.extname(req.url);
            let defaultType = 'text/html';
            if (mime[ext]) {
                defaultType = mime[ext];
            }
            if (defaultType.startsWith('text')) {
                defaultType += '; charset=utf8';
            }
            resp.writeHead(200, {
                'Content-Type': defaultType
            });
            resp.end(fileContent);
        }
    });
};